(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'easydrag'], factory);
    } else {
        factory(window.jQuery);
    }
}(function(a) {

    var css = './bDialog/style.css';
    var fun=null;
    try{
        fun = require[require.toUrl ? 'toUrl' : 'resolve'];
    }catch (err) { }
    if (fun) {
        css = fun(css);
        css = '<link rel="stylesheet" href="' + css + '" />';
        if (a('base')[0]) {
            a('base').before(css);
        } else {
            a('head').append(css);
        }
    }
    var _count = 0;
    var _expando = new Date() - 0;
    var bDialogs={};
    bDialogs.zIndex=1024;

    var bDialog = function(opts,ok,cancel,ele){
        var id = opts.id = opts.id || 'bdialog-'+_expando + _count;

        opts = a.extend(true,{}, bDialog.defaults, opts);

        // 按钮组
        if (!a.isArray(opts.button)){
            opts.button = [];
        }
        // 取消按钮
        cancel && opts.button.push({id: 'cancel', value: opts.cancelVal, callback: cancel}) || opts.cancel && opts.button.push({id: 'cancel', value: opts.cancelVal, callback: opts.cancel});

        //确定按钮
        ok && opts.button.push({id: 'ok', value: opts.okVal, callback: ok}) || opts.ok && opts.button.push({id: 'ok', value: opts.okVal, callback: opts.ok});

        return bDialog.list[id] = new bDialog.create(opts);
    };

    bDialog.create = function(opts){
        var that=this;

        var e = {
            position: function() {
                if(that.c('dialog').width()>this.w[0]){
                    //that.c('dialog').width(this.w[0]-10);
                    that.c('dialog').css('width',(this.w[0]-10)/64+'rem');
                }else if(opts.width){
                    //that.c('dialog').width(opts.width);
                    that.c('dialog').css('width',opts.width/64+'rem');
                }
                if(that.c('dialog').height()>this.w[1]){
                    var dh=that.c('dialog').height()-that.c('body').height();
                    //that.c('body').height(this.w[1]-10-dh);
                    that.c('body').css('height',(this.w[1]-10-dh)/64+'rem');
                }else if(opts.height){
                    //that.c('body').height(opts.height);
                    that.c('body').css('height',opts.height/64+'rem');
                }

                var left = a(window).scrollLeft() + ((this.w[0] - that.c('dialog').outerWidth()) / 2),
                    top = a(window).scrollTop() + ((this.w[1] - that.c('dialog').outerHeight()) / 2);
                //var left = a(window).scrollLeft() + ((this.w[0] - that.c('dialog').width()) / 2),
                //    top = a(window).scrollTop() + ((this.w[1] - that.c('dialog').height()) / 2);
                //that.c('dialog').css({left: left + 'px'}).stop().animate({opacity: 1, top: (top<0?0:top) + 'px'});
                that.c('dialog').hide().css({opacity: 1,left: left,top: (top<0?0:top) }).fadeIn();

            },
            w: [a(window).width(), a(window).height()],
            b: [a('body').outerWidth(true), a('body').outerHeight(true), a('body').css({'overflow':'hidden'})]
            //b: [a('body').width(true), a('body').height(true), a('body').css({'overflow':'hidden'})]
        },
        bg = function() {
            //that.c('maskbg').css({width: (e.w[0] < e.b[0] && e.b[0] || e.w[0])/64 + 'rem', height: (e.w[1] < e.b[1] && e.b[1] || e.w[1])/64 + 'rem'});
            that.c('maskbg').css({width: '100%', height: (e.w[1] < e.b[1] && e.b[1] || e.w[1])/64 + 'rem'});
            opts.quickClose && that.c('maskbg').dblclick(function() {
                that._trigger();
            });
        },
        g = function() {
            e.position();
            a(window).on("resize", function() {
                e.w = [a(window).width(), a(window).height()],
                    e.b = [a('body').outerWidth(true), a('body').outerHeight(true)],
                    //e.b = [a('body').width(true), a('body').height(true)],
                    e.position();
                bg();
            });
            a(window).on("scroll", function() {
                //e.position();
            });
        },
        //获取资源路径
        getfile = function(file) {
            return fun && fun(file) || file;
        };
        this.content= function(txt){
            var body = that.c('body');
            opts.icon && (that.c('body').html(opts.withicon), that.c('icon').append('<img src="' + getfile('./bDialog/icons/' + opts.icon + '.png') + '"/>'), opts.height && that.c('content').height(opts.height), body = that.c('content'));
            txt && body.html(txt) || (
                opts.url && (
                    a.get(opts.url, function(data) {
                        switch (that.datatype) {
                            case 'json':
                                data.status == 1 && (body.html(data.data),e.position()) || (a.isFunction(opts.error) && that.error(data));
                                break;
                            default:
                                (body.html(data),e.position());
                        }
                        a.isFunction(opts.end) && opts.end.call(that);
                    }, opts.datatype)
                ) || (body.html(opts.content),e.position())
            );
        },
        this.init= function() {
            that.dom = a('<div/>');
            that.dom.append(opts.template);
            a('body').append(that.dom);
            that.c('body').html(opts.loading);
            that.dom.attr('id', opts.id);
            __zIndex();

            bg(),
            opts.radius && that.c('dialog').addClass('radius'),
            opts.skin && that.c('dialog').addClass('bdialog-skin-'+opts.skin),
            that.title(opts.title),
            //opts.width && that.c('dialog').width(opts.width),
            //opts.height && that.c('body').height(opts.height),
            opts.width && that.c('dialog').css('width',opts.width/64+'rem'),
            opts.height && that.c('body').css('height',opts.height/64+'rem'),
            opts.padding && that.c('body').css('padding',opts.padding/64+'rem'),
            that.button(opts.button),
            that.content();

            // 按钮组点击
            that.c('dialog').on('click', '[data-id]', function(event) {
                var $this = a(this);
                if (!$this.attr('disabled')) {// IE BUG
                    that._trigger($this.data('id'));
                }
                event.preventDefault();
            });
            that.c('close').click(function() {
                that._trigger();
            });
            g();
        };

        // 置顶浮层
        __zIndex= function () {
            bDialogs.zIndex ++;
            var index = bDialogs.zIndex;
            // 设置叠加高度
            that.c('dialog').css('zIndex', index);
            that.c('maskbg').css('zIndex', index - 1);
            bDialogs.zIndex = index;
        };
        if(opts.zIndex){
            bDialogs.zIndex=opts.zIndex;
        }
        this.init();

        return this;
    };

    bDialog.create.prototype = {
        c:function(s){
            return this.dom.find('[i="' + s + '"]');
        },
        button: function(args) {
            args = args || [];
            var that = this;
            this.callbacks = {},
            this.c('footer')[args.length ? 'show' : 'hide']();

            var html = '';
            if (typeof args === 'string') {
                html = args;
            } else {
                a.each(args, function(i, val) {
                    val.id = val.id || val.value;
                    that.callbacks[val.id] = val.callback;

                    html += '<button type="button" data-id="' + val.id + '">' + val.value + '</button>';
                });
            }
            that.c('footer').html(html);
            return this;
        },
        _trigger: function(id) {
            var fn = this.callbacks[id];
            return typeof fn !== 'function' || fn.call(this) !== false ? (this.remove()) : this;
        },
        //=====================================================================
        //关闭（隐藏）对话框。
        close: function() {
            this.c('dialog').hide();
            this.c('maskbg').hide();
        },
        //销毁对话框
        remove:function() {
            var that=this;
            that.c('dialog').animate({opacity: 0},300, function() {
                var dl=a(this);
                that.c('maskbg').fadeOut(200, function() {
                    dl.remove();
                    a(this).remove();
                    that.dom.remove();
                    a('body').css({'overflow':'auto'});
                });

            });
        },
        show:function() {
            var that=this;
            that.c('maskbg').fadeIn(function() {
                that.c('dialog').fadeIn();
            });
        },
        title:function(txt){
            this.c('title').text(txt);
            this.c('header')[txt ? 'show' : 'hide']();
            txt && (this.c('dialog').easydrag(), this.c('dialog').setHandler(this.c('header')));
            return this;
        },

        time:function(times,callback){
            var that=this;
            setTimeout(function(){
                that.remove();
                $.isFunction(callback) && callback(this);
            },times*1000);
        }
    };
    /**
    * 根据 ID 获取某对话框 API
    * @param    {String}    对话框 ID
    * @return   {Object}    对话框 API (实例)
    */
    bDialog.get = function (id) {
       return id === undefined ? bDialog.list : bDialog.list[id];
    };
    bDialog.list ={};

    bDialog.defaults = {
        // 确定按钮回调函数
        ok: null,
        // 取消按钮回调函数
        cancel: null,
        // 确定按钮文本
        okVal: '确定',
        // 取消按钮文本
        cancelVal: '关闭',
        // 自定义按钮
        button: null,
        // 是否支持快捷关闭（点击遮罩层自动关闭）
        quickClose: false,
        datatype: 'html',
        //zIndex: 1024,
        width:null,
        height:null,
        radius: 1, //设置对话框： 0:直角，1：圆角
        loading: '<div class="bdialog-loading"><div class="bdialog-loading-content bdialog-inline-block">加载中，请稍候 ...</div></div>',
        withicon: '<table class="bdialog-info"><tr><td class="icon" i="icon" valign="middle"></td><td class="bdialog-conent" i="content"></td></tr></table>',
        template: '<div class="bdialog" i="dialog">'
                + '<div class="bdialog-header" i="header"><span class="bdialog-title" i="title"></span><span title="关闭" i="close" class="bdialog-icon-close"></span></div>'
                + '<div class="bdialog-body" i="body"></div>'
                + '<div class="bdialog-footer" i="footer"></div>'
                + '</div><div class="bdialog-mask" i="maskbg"></div>'
    };

    window.bDialog=bDialog;

    return bDialog;
}));